package com.huika.renrench.control.common.base;

import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.lib.base.R;
import com.huika.lib.ui.framelayout.fragment.BaseFragment;
import com.huika.lib.ui.widget.LoadingDialog;
import com.huika.lib.ui.widget.ToastMsg;
import com.huika.lib.ui.widget.overlay.OverlayLayout;
import com.huika.renrench.http.ServerFlagError;


public abstract class BaseFra extends BaseFragment implements ErrorListener, OnCancelListener{
	/**
	 * 嵌套viewpager时，第一次显示回调
	 * @author fanxing 创建于 Dec 3, 2014
	 */
	public interface OnInitShowListener{
		void onInitShow();
	}
	protected View netErrorView;
	
	
	/** 分页加载数据，每页数据量 */
	protected static final int PAGE_SIZE = 10;
	/** 当前页，用于分页加载数据 */
	protected int CURRENT_PAGE = 1;
	
	protected LoadingDialog loadingDialog;
	protected OverlayLayout mOverlayLayout;
	
	protected void initLoadingDialog(boolean isTrans){
		if (null == loadingDialog) {
			loadingDialog = new LoadingDialog(getActivity(), isTrans);
			loadingDialog.setOnCancelListener(this);
		}
	}
	
	public void showLoadingDialog(String parameter) {
		initLoadingDialog(true);//透明
		loadingDialog.setTitle(parameter);
		if(!loadingDialog.isShowing())
			loadingDialog.show();
	}
	
	/**
	 * show to @param(cls)，but can't finish activity
	 */
	public void showActivity(Activity aty, Class<?> cls) {
		Intent intent = new Intent();
		intent.setClass(aty, cls);
		aty.startActivity(intent);
		getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}

	/**
	 * show to @param(cls)，but can't finish activity
	 */
	public void showActivity(Activity aty, Intent it) {
		aty.startActivity(it);
		getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}

	/**
	 * show to @param(cls)，but can't finish activity
	 */
	public void showActivity(Activity aty, Class<?> cls, Bundle extras) {
		Intent intent = new Intent();
		intent.putExtras(extras);
		intent.setClass(aty, cls);
		aty.startActivity(intent);
		getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}
	
	@Override
	public void onCancel(DialogInterface dialog) {}

	public void dismissLoadingDialog() {
		if (null != loadingDialog) {
			LoadingDialog.dismissDialog(loadingDialog);
		}
	}
	
	public void showToastMsg(String msg) {
		ToastMsg.showToastMsg(getActivity(), msg);
	}

	public void showToastMsg(int strId) {
		ToastMsg.showToastMsg(getActivity(), strId);
	}
	
	private Set<Object> tags = new HashSet<Object>();
	/**
	 * 添加网络请求
	 * @param request
	 */
	protected void executeRequest(Request request){
		VolleyRequestManager.addRequest(request, this);
		tags.add(this);
	}
	/**
	 * 添加网络请求
	 * @param request
	 */
	protected void executeRequest(Request request, Object tag){
		VolleyRequestManager.addRequest(request, tag);
		tags.add(tag);
	}
	/**
	 * 取消网络请求
	 * @param tag
	 */
	protected void cancelRequest(Object tag){
		VolleyRequestManager.cancelAll(tag);
	}
	
	@Override
	public void onStop() {
		super.onStop();
		for (Object tag : tags) {
			VolleyRequestManager.cancelAll(tag);
		}
	}
	
	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}
	
	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
		getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_right_out);
	}
	
	//默认网络请求异常回调
	@Override
	public void onErrorResponse(VolleyError error) {
		dismissLoadingDialog();

		String msg = "网络异常";
		if(error instanceof ServerFlagError){
			msg = ((ServerFlagError)error).result.msg;
		}else{
			try {
				if (error.networkResponse != null && error.networkResponse.data != null)
					msg = new String(error.networkResponse.data, "utf-8");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		showToastMsg(msg);
	}
	
	/**要在Fragment中监听按键需要实现该接口*/
	public interface FragmentKeyDown{
		boolean onFraKeyDown(int keyCode, KeyEvent event);
	}
	
	
	/**覆盖页******************************/
	protected void showOverLay(){
		if(mOverlayLayout != null){
			mOverlayLayout.showOverlay();
		}
	}
	
	protected void hideOverLay(){
		if(mOverlayLayout != null){
			mOverlayLayout.hideOverlay();
		}
	}
	
	/***
	 * 事件监听view的id=R.id.click_reload
	 * 显示加载异常
	 * 
	 * @param reloadListener
	 */
	protected void setNetErrorClick(View.OnClickListener reloadListener) {
		initNetErrorView();
		if (reloadListener != null){
			netErrorView.findViewById(R.id.click_reload).setOnClickListener(reloadListener);
			netErrorView.findViewById(R.id.click_checknetwork).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// 检查网络设置
					Intent intent= new Intent();
                	ComponentName component = new ComponentName("com.android.settings", "com.android.settings.Settings");
                    intent.setComponent(component);
                    intent.setAction("android.intent.action.VIEW");
	                getActivity().startActivity(intent);
				}
			});
			
		}
	}
	protected View initNetErrorView(){
		if (netErrorView == null) {
			initOverlayLayout();
			netErrorView=mOverlayLayout.setOverlayView(R.layout.common_load_error);
		}
		return netErrorView;
	}
	protected void initOverlayLayout(){
		if(mOverlayLayout==null)
			mOverlayLayout=new OverlayLayout(getActivity());
	}
	
	
	/**设置overlay依附的viewgroup*/
	protected void setOverLayAttachTo(View targetView){
		initOverlayLayout();
		mOverlayLayout.attachTo(targetView);
	}
	
	
	/**覆盖页 end******************************/
	
	/* 获取输入内容 */
	public String getInputStr(EditText et) {
		return et.getText().toString().trim();
	}
	/**
	 * @Description:关闭键盘事件
	 * @author: 刘成伟（wwwlllll@126.com）
	 * @Title: closeInput
	 * @param
	 * @return void
	 * @throws
	 * @date 2014-4-6 上午11:18:36
	 */
	public void closeInput() {
		InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (inputMethodManager != null && getActivity().getCurrentFocus() != null) {
			inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
}
